package xin.marcher.module.inventory.util;

import xin.marcher.module.common.utils.HashUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库存工具方法
 */
public class InventorBucketUtil {

    private static final int MAX_SIZE = 100000;

    /**
     * 生成对应的槽位key 默认的
     *
     * @param key       卖家Id+商品skuId
     * @param bucketNum 分桶配置数量
     * @return 预先保留的槽位集合
     */
    public static List<String> createBucketNoList(String key, Integer bucketNum) {
        return createBucketNoList(key, bucketNum, "%06d");
    }

    /**
     * 生成对应的槽位 key 明细使用，多使用一位区分
     *
     * @param key       卖家Id+商品skuId
     * @param bucketNum 分桶配置数量
     * @return 预先保留的槽位集合
     */
    public static List<String> createBucketNoList(String key, Integer bucketNum, String format) {
        Map<Long, String> bucketIndex2BucketNoMap = new HashMap<>(bucketNum);
        List<String> bucketNoList = new ArrayList<>(bucketNum);
        for (int i = 1; i <= MAX_SIZE; i++) {
            String serialNum = String.format(format, i);
            String bucketNo = key + serialNum; // 卖家+商品+序号
            long hash = HashUtil.murMurHash(bucketNo.getBytes());
            // c: 是某一个分桶位置
            long bucketIndex = hash % bucketNum;   // hash 作为编号是对应哪个分桶, 路由到一个分桶
            if (bucketIndex2BucketNoMap.containsKey(bucketIndex)) {
                continue;
            }
            bucketIndex2BucketNoMap.put(bucketIndex, bucketNo);
            bucketNoList.add(bucketNo);
            if (bucketIndex2BucketNoMap.size() >= bucketNum) {
                break;
            }
        }
        return bucketNoList;
    }

    /**
     * 根据订单ID 定位到具体的分片槽位
     *
     * @param orderId
     * @param bucketNum
     * @return
     */
    public static Long createDetailBucketKey(String orderId, Integer bucketNum) {
        Long hash = Long.valueOf(orderId);
        long index = hash %= bucketNum;

        return index;
    }

    public static void main(String[] args) {
        List<String> bucketNoList = createBucketNoList("1080000001", 32, "%07d");

        for (int i = 0; i < bucketNoList.size(); i++) {
            String inventoryDetailKey = bucketNoList.get(i);

            long hash = HashUtil.murMurHash(inventoryDetailKey.getBytes());
            long c = (hash %= 32);

            System.out.println("对应下标：" + c);
        }
    }


}
